<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="90px">
      <!-- <el-form-item label="班次ID" prop="shiftId">
        <el-input
          v-model="queryParams.shiftId"
          placeholder="请输入班次ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="所属班次" prop="shiftId">
        <el-select
          v-model="queryParams.shiftId"
          placeholder="请选择所属班次"
          clearable
          filterable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in shiftOptions"
            :key="item.shiftId"
            :label="item.shiftName"
            :value="item.shiftId"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="生产线ID" prop="lineId">
        <el-input
          v-model="queryParams.lineId"
          placeholder="请输入生产线ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="所属生产线" prop="lineId">
        <el-select
          v-model="queryParams.lineId"
          placeholder="请选择所属生产线"
          clearable
          filterable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in lineOptions"
            :key="item.lineId"
            :label="item.lineName"
            :value="item.lineId"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="车间ID" prop="workshopId">
        <el-input
          v-model="queryParams.workshopId"
          placeholder="请输入车间ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="所属车间" prop="workshopId">
        <el-select v-model="queryParams.workshopId" placeholder="请选择所属车间" clearable>
          <el-option
            v-for="item in workshopOptions"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="排班日期" style="width: 308px">
        <el-date-picker
          v-model="daterangeScheduleDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="团队ID" prop="teamId">
        <el-input
          v-model="queryParams.teamId"
          placeholder="请输入团队ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <el-form-item label="所属团队" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择所属团队" clearable>
          <el-option
            v-for="item in teamOptions"
            :key="item.teamId"
            :label="item.teamName"
            :value="item.teamId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工数量" prop="employeeCount">
        <el-input
          v-model="queryParams.employeeCount"
          placeholder="请输入员工数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划产出" prop="planOutput">
        <el-input
          v-model="queryParams.planOutput"
          placeholder="请输入计划产出"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实际产出" prop="actualOutput">
        <el-input
          v-model="queryParams.actualOutput"
          placeholder="请输入实际产出"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in sm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['sm:schedule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sm:schedule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sm:schedule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sm:schedule:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="排班ID" align="center" prop="scheduleId" />
      <el-table-column label="班次名称" align="center" prop="shiftName" />
     <!-- <el-table-column label="班次名称" align="center" prop="shiftName" /> -->
      <el-table-column label="开始时间" align="center" prop="startTime">
        <template #default="scope">
          {{ printTimeInfo(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime">
        <template #default="scope">
          {{ printTimeInfo(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="生产线" align="center" prop="lineName" />
      <el-table-column label="车间" align="center" prop="workshopName" />
      <el-table-column label="排班日期" align="center" prop="scheduleDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.scheduleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="员工数量" align="center" prop="employeeCount" />
      <el-table-column label="计划产出" align="center" prop="planOutput" />
      <el-table-column label="实际产出" align="center" prop="actualOutput" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sm_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sm:schedule:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sm:schedule:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班次排班对话框 -->
    <!-- 修改对话框部分代码 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="scheduleRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班次" prop="shiftId">
              <el-select
                v-model="form.shiftId"
                placeholder="请选择班次"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in shiftOptions"
                  :key="item.shiftId"
                  :label="item.shiftName"
                  :value="item.shiftId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="生产线" prop="lineId">
              <el-select
                v-model="form.lineId"
                placeholder="请选择生产线"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in lineOptions"
                  :key="item.lineId"
                  :label="item.lineName"
                  :value="item.lineId"
                />
              </el-select>
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
  <el-form-item label="所属生产线" prop="lineId">
    <el-input v-model="form.lineName" placeholder="请选择生产线" disabled>
      <template #append>
        <el-button type="primary" @click="handleSelectLine">选择生产线</el-button>
      </template>
    </el-input>
    <el-input v-model="form.lineId" type="hidden" />
  </el-form-item>
</el-col>

          <el-col :span="12">
            <el-form-item label="车间" prop="workshopId">
              <el-select
                v-model="form.workshopId"
                placeholder="请选择车间"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in workshopOptions"
                  :key="item.workshopId"
                  :label="item.workshopName"
                  :value="item.workshopId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班日期" prop="scheduleDate">
              <el-date-picker
                v-model="form.scheduleDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择排班日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属团队" prop="teamId">
              <el-select v-model="form.teamId" placeholder="请选择所属团队" clearable>
                <el-option
                  v-for="item in teamOptions"
                  :key="item.teamId"
                  :label="item.teamName"
                  :value="item.teamId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="员工数量" prop="employeeCount">
              <el-input
                v-model="form.employeeCount"
                placeholder="请输入员工数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划产出" prop="planOutput">
              <el-input
                v-model="form.planOutput"
                placeholder="请输入计划产出"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际产出" prop="actualOutput">
              <el-input
                v-model="form.actualOutput"
                placeholder="请输入实际产出"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="form.status"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in sm_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <LineSelect ref="lineSelectRef" />
  </div>
</template>

<script setup name="Schedule">
import { listSchedule, getSchedule, delSchedule, addSchedule, updateSchedule,listLine,listWorkshop,listShift,listTeam } from "@/api/sm/schedule";
const teamOptions = ref([]);
const { proxy } = getCurrentInstance();
const { sm_status } = proxy.useDict('sm_status');
const lineOptions = ref([]);
const shiftOptions = ref([]);
const workshopOptions = ref([]);
const scheduleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeScheduleDate = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shiftId: null,
    lineId: null,
    workshopId: null,
    scheduleDate: null,
    teamId: null,
    employeeCount: null,
    planOutput: null,
    actualOutput: null,
    status: null,
  },
  rules: {
    shiftId: [
      { required: true, message: "班次ID不能为空", trigger: "blur" }
    ],
    lineId: [
      { required: true, message: "生产线ID不能为空", trigger: "blur" }
    ],
    workshopId: [
      { required: true, message: "车间ID不能为空", trigger: "blur" }
    ],
    scheduleDate: [
      { required: true, message: "排班日期不能为空", trigger: "blur" }
    ],
    teamId: [
      { required: true, message: "团队ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询班次排班列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeScheduleDate && '' != daterangeScheduleDate) {
    queryParams.value.params["beginScheduleDate"] = daterangeScheduleDate.value[0];
    queryParams.value.params["endScheduleDate"] = daterangeScheduleDate.value[1];
  }
  listSchedule(queryParams.value).then(response => {
    scheduleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    scheduleId: null,
    shiftId: null,
    lineId: null,
    workshopId: null,
    scheduleDate: null,
    teamId: null,
    employeeCount: null,
    planOutput: null,
    actualOutput: null,
    status: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("scheduleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeScheduleDate.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.scheduleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加班次排班";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _scheduleId = row.scheduleId || ids.value
  getSchedule(_scheduleId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改班次排班";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scheduleRef"].validate(valid => {
    if (valid) {
      if (form.value.scheduleId != null) {
        updateSchedule(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addSchedule(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _scheduleIds = row.scheduleId || ids.value;
  proxy.$modal.confirm('是否确认删除班次排班编号为"' + _scheduleIds + '"的数据项？').then(function() {
    return delSchedule(_scheduleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sm/schedule/export', {
    ...queryParams.value
  }, `schedule_${new Date().getTime()}.xlsx`)
}

import LineSelect from '@/components/LineSelect/index.vue';

const lineSelectRef = ref();

function handleSelectLine() {
  if (!lineSelectRef.value) {
    proxy.$modal.msgError("生产线选择组件初始化失败");
    return;
  }
  
  try {
    lineSelectRef.value.show();
    
    lineSelectRef.value.onSelect((selectedLine) => {
      form.value.lineId = selectedLine.lineId;
      form.value.lineName = selectedLine.lineName;
    });
  } catch (error) {
    proxy.$modal.msgError("打开生产线选择失败：" + error.message);
    console.error(error);
  }
}

// 显示调试信息
function printTimeInfo(time) {
  if (!time) return '';
  // 直接调用格式化函数处理时间
  return formatTime(time);
}

function formatTime(timeStr) {
  if (!timeStr) return "";
  
  // 如果已经是HH:mm:ss格式，直接返回
  if (/^\d{2}:\d{2}:\d{2}$/.test(timeStr)) {
    return timeStr;
  }
  
  // 尝试处理可能的日期时间格式
  try {
    // 首先尝试提取时间部分
    const timeMatch = timeStr.match(/\d{2}:\d{2}:\d{2}/);
    if (timeMatch) {
      // 如果字符串中包含时间格式，直接提取
      return timeMatch[0];
    }
    
    // 处理ISO格式或其他格式的时间
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) {
      console.error("无效的时间格式:", timeStr);
      return timeStr;
    }
    
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    
    return `${hours}:${minutes}:${seconds}`;
  } catch (e) {
    console.error("时间格式化错误:", e);
    return timeStr;
  }
}


// 在组件挂载时获取车间选项
onMounted(() => {
  // 获取车间列表
  listWorkshop().then(response => {
    workshopOptions.value = response.rows || response.data;
  });
    // 获取生产线列表
    listLine().then(response => {
    lineOptions.value = response.rows || response.data;
  });

      // 获取班次列表
      listShift().then(response => {
        shiftOptions.value = response.rows || response.data;
  });
    // 获取团队列表
    listTeam().then(response => {
    teamOptions.value = response.rows || response.data;
  });

 
  getList();
});
</script>
